package com.yiyi.system.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.yiyi.common.utils.DateUtils;
import com.yiyi.system.domain.ConversionType;
import com.yiyi.system.domain.MarketingBaidu;
import com.yiyi.system.domain.MarketingData;
import com.yiyi.system.mapper.MarketingBaiduMapper;
import com.yiyi.system.mapper.MarketingDataMapper;
import com.yiyi.system.service.IMarketingDataService;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author yiyi
 * @date 2025-01-21
 */
@Service
public class MarketingDataServiceImpl implements IMarketingDataService
{
    @Autowired
    private MarketingDataMapper marketingDataMapper;
    @Autowired
    private MarketingBaiduMapper marketingBaiduMapper;

    /***
     * 百度推广  ocpc
     */
    private static final Integer RETRY_TIMES = 3;
    private static final String BAIDU_OCPC_URL = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData";

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public MarketingData selectMarketingDataById(Long id)
    {
        return marketingDataMapper.selectMarketingDataById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param marketingData 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<MarketingData> selectMarketingDataList(MarketingData marketingData)
    {
        return marketingDataMapper.selectMarketingDataList(marketingData);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param marketingData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertMarketingData(MarketingData marketingData)
    {
        marketingData.setCreateTime(DateUtils.getNowDate());
        return marketingDataMapper.insertMarketingData(marketingData);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param marketingData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateMarketingData(MarketingData marketingData)
    {
        marketingData.setUpdateTime(DateUtils.getNowDate());
        return marketingDataMapper.updateMarketingData(marketingData);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteMarketingDataByIds(Long[] ids)
    {
        return marketingDataMapper.deleteMarketingDataByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteMarketingDataById(Long id)
    {
        return marketingDataMapper.deleteMarketingDataById(id);
    }

    /**
     * 添加营销数据
     *
     */
    @Transactional
    @Override
    public int addMarketingData(MarketingData marketingData)
    {
        marketingData.setCreateTime(DateUtils.getNowDate());
        MarketingBaidu marketingBaidu=new MarketingBaidu();
        marketingBaidu.setMarketingLink(marketingData.getDomainUrl());
        marketingBaiduMapper.updateMarketingData(marketingBaidu);
        return marketingDataMapper.insertMarketingData(marketingData);
    }


    /**
     *ocpc回传
     */
    public boolean ocpc(ConversionType conversionType){
        boolean result=true;
        String token = conversionType.getToken();
        List<ConversionType> conversionTypes = new ArrayList<>();
        // 编辑一条转化数据
        ConversionType cv = new ConversionType();
        cv.setLogidUrl(conversionType.getLogidUrl()); // 设置落地页url
        cv.setConvertType(conversionType.getNewType()); // 设置转化类型
        cv.setNewType(conversionType.getNewType());  // 设置转化类型
        conversionTypes.add(cv);
        try {
            sendConvertData(token, conversionTypes);
        }catch (Exception e){
            result=false;
        }
        return result;
    }


    private static Boolean sendConvertData(String token, List<ConversionType> conversionTypeList) {

        JsonObject data = new JsonObject();
        // 设置API接口回传Token
        data.addProperty("token", token);
        // 设置API接口回传conversionTypes
        data.add("conversionTypes",
                new Gson().toJsonTree(conversionTypeList, new TypeToken<List<ConversionType>>() {}.getType()).getAsJsonArray());
        // 发送的完整请求数据
        // do some log
        System.out.println("req data: " + data.toString());
        // 向百度发送数据
        return sendWithRetry(data.toString());

    }

    private static boolean sendWithRetry(String msg) {
        // 发送请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(BAIDU_OCPC_URL);
        post.setHeader("Content-type", "application/json; charset=UTF-8");
        StringEntity entity = new StringEntity(msg, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        post.setEntity(entity);
        // 添加失败重试
        int retry = RETRY_TIMES;
        for (int i = 0; i < retry; i++) {
            try {
                HttpResponse response = client.execute(post);
                // 检验状态码，如果成功接收数据
                int code = response.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    String res = EntityUtils.toString(response.getEntity());
                    JsonObject returnData = new JsonParser().parse(res).getAsJsonObject();
                    // 打印返回结果
                    // do some log
                    System.out.println("retry times :" + i + ", res data: " + res);

                    int status = returnData.getAsJsonObject("header").get("status").getAsInt();
                    System.err.println("status == 0 代表回传数据成功，其余情况回传数据失败>>>>"+status);
                    // status为4，代表服务端异常，可添加重试
                    if ( status != 4) {
                        return status == 0; // status == 0 代表回传数据成功，其余情况回传数据失败
                    }
                }
            } catch (IOException e) {
                System.err.println("status == 0 代表回传数据失败>>>>");
            }
        }
        return false;
    }
}
